<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--侧边部门数据-->
      <el-col :lg="4" :md="4" :sm="6" :xl="4" :xs="9">
        <div class="head-container">
          <el-input
              v-model="deptName"
              class="filter-item"
              clearable
              placeholder="输入部门名称搜索"
              prefix-icon="el-icon-search"
              size="small"
              @input="getDeptDatas"
          />
        </div>
        <el-tree
            :data="deptDatas"
            :expand-on-click-node="false"
            :props="defaultProps"
            default-expand-all
            @node-click="handleNodeClick"
        />
      </el-col>
      <!--用户数据-->
      <el-col :lg="20" :md="20" :sm="18" :xl="20" :xs="15">
        <!--工具栏-->
        <div class="head-container">
          <el-row>
            <el-col span="4">
              <el-input
                v-model="query.keyword"
                class="filter-item"
                clearable
                placeholder="输入名称或者邮箱搜索"
                size="small"
                style="width: 100%"
                @keyup.enter.native="crud.toQuery"
              />
            </el-col>
            <el-col span="4">
              <el-select
                v-model="query.status"
                class="filter-item"
                clearable
                placeholder="状态"
                size="small"
                style="width: 100%"
                @change="crud.toQuery"
              >
                <el-option
                  v-for="item in enabledTypeOptions"
                  :key="item.key"
                  :label="item.display_name"
                  :value="item.key"
                />
              </el-select>
            </el-col>
            <el-col span="4">
              <el-input
                v-model="query.postName"
                class="filter-item"
                clearable
                placeholder="输入岗位名称搜索"
                size="small"
                style="width: 100%"
                @keyup.enter.native="crud.toQuery"
              />
            </el-col>
            <el-col span="4">
              <table-select
                style="width: 100%"
                :tableColumns="
                  [
                  {prop:'code',label:'客户编码',width: '100'},
                  {prop:'name',label:'客户名称',width: '150'},
                  ]"
                labelKey="name"
                valueKey="id"
                width="400"
                :value.sync="query.sCustomerIds"
                placeholder="请选择绑定客户"
                url="/api/dropDown/basCustomerList"
              ></table-select>
            </el-col>
          </el-row>
          <el-row>
            <el-col span="4">
              <zSelect :value.sync="query.saleSystemIds" :showName="form.saleSystemName" url="api/dropDown/basSaleSystemList" style="width:  370px;"/>
            </el-col>
            <el-col span="4">
              <treeselect
                style="width: 200px;height:30px;display: inline-block"
                v-model="query.customerAreaIds"
                :options="areaList"
                placeholder="客户区域"
                :normalizer="normalizer"
                multiple
                @input="val=>getNoStr(val,'areaList','customerAreaIds')"
              />

            </el-col>

          </el-row>
          <div v-if="crud.props.searchToggle">
            <!-- 搜索 -->

            <el-button
              class="filter-item"
              size="mini"
              type="primary"
              @click="crud.toQuery"
            >
              搜索
            </el-button>
            <el-button
              class="filter-item"
              plain
              size="mini"
              type="primary"
              @click="crud.resetQuery()"
            >
              重置
            </el-button>
          </div>
          <crudOperation :permission="permission" show="">
            <el-button
              slot="right"
              class="filter-item"
              size="mini"
              type="success"
              :disabled="crud.selections.length == 0"
              @click="refashPass(crud.selections)"
            >重置密码
            </el-button>
          </crudOperation>
        </div>
        <el-dialog :before-close="flag" :close-on-click-modal="false" :title="title"
                   :visible.sync="flag" append-to-body width="50%" height='450px'>
          <el-form ref="target-form" :inline="true" :model="query"  label-width="120px" size="small">
            <el-form-item label="年份">
              <!-- <el-input v-model="query.year" @change="inyear"/> -->
              <el-select
                v-model="query.year"
                class="filter-item"
                clearable
                placeholder="年份"
                size="small"
                style="width: 100%"
                @change="inyear"
              >
                <el-option
                  v-for="item in years"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <!-- <el-form-item label="月份"><el-input v-model="query.month"/></el-form-item> -->
            <!-- <el-form-item label="每日任务数"><el-input v-model="query.dayTarget"/></el-form-item>
            <el-form-item label="每月任务数"><el-input v-model="query.monthTarget"/></el-form-item> -->
            <target :targetlist="targetlist" :date='date' @section="section"></target>
            <!-- <el-pagination
              :current-page.sync="query.targetpage"
              :page-sizes="[10, 20, 50, 100]"
              :page-size="query.targetsize"
              layout="total, prev, pager, next,sizes"
              :total="query.total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
      /> -->
      <div >
        <el-button style=" margin: 10px 0px 10px 90%" type="primary" @click="save">确认</el-button>
      </div>

          </el-form>
        </el-dialog>
        <!--表单渲染-->
        <el-dialog :before-close="crud.cancelCU" :close-on-click-modal="false" :title="crud.status.title"
                   :visible.sync="crud.status.cu > 0" append-to-body width="1100px">
          <el-form ref="form" :inline="true" :model="form" :rules="rules" label-width="120px" size="small">
            <el-button type="primary" @click="target">指标</el-button>
            <el-divider content-position="left">基本信息</el-divider>
            <el-row>
              <el-col :span="8">
                <el-form-item label="用户头像" prop="imageUrl">
                  <el-upload
                    ref="upload"
                    class="avatar-uploader"
                    :show-file-list="false"
                    :headers="headers"
                    :on-error="handleError"
                    :before-upload="beforeAvatarUpload"
                    :on-success="handleAvatarSuccess"
                    :action="action"
                  >
                    <img v-if="form.avatar" :src="form.avatar" class="avatar">
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                  </el-upload>

                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="登录名" prop="loginName">
                  <el-input v-model="form.loginName"/>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="电话" prop="phone">
                  <el-input v-model="form.phone" maxlength="11" oninput="value=value.replace(/[^\d]/g,'')" show-word-limit/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item label="昵称" prop="">
                  <el-input v-model="form.nickName" maxlength="20" show-word-limit/>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="邮箱" prop="">
                  <el-input v-model="form.email"/>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="用户编码" prop="code">
                  <el-input v-model="form.code"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item label="紧急联系人" prop="contactName">
                  <el-input v-model="form.contactName"/>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="紧急联系电话" prop="contactPhone">
                  <el-input v-model="form.contactPhone"/>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="部门" prop="deptId">
                  <treeselect
                    v-model="form.deptId"
                    :options="depts"
                    placeholder="选择部门"
                    style="width:185px"
                    @select="selectFun"
                    :normalizer="normalizer"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item v-if="form.pid !== 0" label="公司" prop="pid" >
                  <treeselect v-model="form.companyId" :normalizer="normalizer"    style="width:185px" :options="companyDatas" placeholder="选择公司"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="岗位" prop="postId">
                  <el-select v-model="form.postId"  style="width:185px"  placeholder="请先选择岗位" >
                    <el-option
                      v-for="(item, index) in jobs"
                      :key="item.name + index"
                      :label="item.name"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="角色" prop="roles" style="margin-bottom: 0;">
                  <el-select
                    v-model="form.roles"
                    multiple
                    style="width:185px"
                    placeholder="请选择角色"
                    @change="changeRole"
                    @remove-tag="deleteTag"
                  >
                    <el-option
                      v-for="item in roles"
                      :label="item.name"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>



          <el-form-item label="业务属性">
            <el-checkbox-group v-model="businessAttrNum">
              <el-checkbox
                v-for="item in dict.t_sys_user_business_attr"
                :key="item.value"
                :label="item.label"
                name="kmchk"
                @change="handleChange($event,item)"></el-checkbox>
            </el-checkbox-group>
          </el-form-item>
<!--            <el-form-item label="性别">-->
<!--              <el-radio-group v-model="form.sex" style="width: 178px">-->
<!--                <el-radio label="男">男</el-radio>-->
<!--                <el-radio label="女">女</el-radio>-->
<!--              </el-radio-group>-->
<!--            </el-form-item>-->
            <el-form-item label="用户状态">
<!--              <el-switch-->
<!--                v-model="form.status == '1'"-->
<!--                @change="changeEnabledPlus(form.status)"-->
<!--              >-->
<!--              </el-switch>-->
              <el-switch v-model="switchStatus"
                         active-text="启用"
                         inactive-text="禁用"
                         @change="upStatus"
              >
              </el-switch>
<!--              <el-select-->
<!--                :disabled="form.id === user.id"-->
<!--                v-model="form.status"-->
<!--                class="filter-item"-->
<!--                clearable-->
<!--                style="width: 190px"-->
<!--                placeholder="状态"-->
<!--                size="small"-->
<!--                @change="crud.toQuery"-->
<!--              >-->
<!--                <el-option-->
<!--                  v-for="item in enabledTypeOptions"-->
<!--                  :key="item.key"-->
<!--                  :label="item.display_name"-->
<!--                  :value="item.key"-->
<!--                />-->
<!--              </el-select>-->
            </el-form-item>
            <el-col :span="8">
              <el-form-item label="是否直营" prop="isDirectSale">
                <el-select v-model="form.isDirectSale">
                  <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-divider content-position="left">身份信息</el-divider>
            <el-row>
              <el-col :span="8">
                <el-form-item label="姓名" prop="realName">
                  <el-input v-model="form.realName"/>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="身份证号" prop="">
                <el-input v-model="form.idcard"/>
              </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="性别">
                  <el-select
                    v-model="form.sex"
                    style="width:185px"
                    placeholder="请选择性别"
                  >
                    <el-option
                      v-for="item in dict.t_sys_user_sex"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>

            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item label="婚姻状态" prop="marriage">
                  <el-select
                    v-model="form.marriage"
                    style="width:185px"
                    placeholder="请选择婚姻状态"
                  >
                    <el-option
                      v-for="item in dict.t_sys_marriage"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="政治面貌" prop="">
                  <el-select
                    v-model="form.politic"
                    style="width:185px"
                    placeholder="请选择政治面貌"
                  >
                    <el-option
                      v-for="item in dict.t_sys_politic"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="民族" prop="">
                  <el-input v-model="form.nation"/>
                </el-form-item>
              </el-col>
            </el-row>


            <el-row>
              <el-col :span="8">
                <el-form-item label="学历" prop="education">
                  <el-input v-model="form.education"/>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="户籍" prop="householdNature">
                  <el-input v-model="form.householdNature"/>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="户籍地址" prop="householdAddress">
                  <el-input v-model="form.householdAddress"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item label="居住地址" prop="address">
                  <el-input v-model="form.address"/>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="毕业院校" prop="graduateSchool">
                  <el-input v-model="form.graduateSchool"/>
                </el-form-item>
              </el-col>
            </el-row>

            <el-divider content-position="left">合同信息</el-divider>

            <el-row>
              <el-col :span="8">
                <el-form-item label="入职日期" prop="hireDate">
                  <el-date-picker
                    v-model="form.hireDate"
                    type="date"
                    style="width:185px"
                    format="yyyy - MM - dd "
                    value-format="yyyy-MM-dd"
                    placeholder="选择日期">
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="转正日期" prop="positiveDate">
                  <el-date-picker
                    v-model="form.positiveDate"
                    type="date"
                    style="width:185px"
                    format="yyyy - MM - dd "
                    value-format="yyyy-MM-dd"
                    placeholder="选择日期">
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="劳动合同开始日期" prop="contractStartDate">
                  <el-date-picker
                    v-model="form.contractStartDate"
                    type="date"
                    style="width:185px"
                    format="yyyy - MM - dd "
                    value-format="yyyy-MM-dd"
                    placeholder="选择日期">
                  </el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="8">
                <el-form-item label="劳动合同结束日期" prop="contractEndDate">
                  <el-date-picker
                    v-model="form.contractEndDate"
                    type="date"
                    style="width:185px"
                    format="yyyy - MM - dd "
                    value-format="yyyy-MM-dd"
                    placeholder="选择日期">
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="工资标准" prop="salaryStand">
                  <el-input v-model="form.salaryStand"/>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="工资卡号" prop="salaryCard">
                  <el-input v-model="form.salaryCard"/>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="8">
                <el-form-item label="其他福利" prop="otherBenefits">
                  <el-input v-model="form.otherBenefits"/>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="退休日期" prop="retireDate">
                  <el-date-picker
                    v-model="form.retireDate"
                    type="date"
                    style="width:185px"
                    format="yyyy - MM - dd "
                    value-format="yyyy-MM-dd"
                    placeholder="选择日期">
                  </el-date-picker>

                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="离职日期" prop="leaveDate">
                  <el-date-picker
                    v-model="form.leaveDate"
                    type="date"
                    style="width:185px"
                    format="yyyy - MM - dd "
                    value-format="yyyy-MM-dd"
                    placeholder="选择日期">
                  </el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>


            <el-row>
              <el-col :span="8">
                <el-form-item label="离职原因" prop="leaveRemark">
                  <el-input v-model="form.leaveRemark"/>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="工资方案" prop="payPlanId">
                  <zSelect
                  multiple
                  :value.sync="payPlanId"
                  :showName='payPlanName'
                           :labelKey="'planName'"
                           url="/api/dropDown/payPlanList"
                           style="width: 100%;"/>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="班次定义" prop="scheduleId">
                  <zSelect
                  :value.sync="form.scheduleId"
                           url="/api/dropDown/basScheduleList"
                           style="width: 100%;"/>
                </el-form-item>
              </el-col>
            </el-row>


            <el-divider content-position="left">其他信息</el-divider>
<!--            <div class="line-tips">其他信息</div>-->
            <el-row>
              <el-col :span="8">
                <el-form-item label="业余爱好(特长)" prop="hobbies">
                  <el-input v-model="form.hobbies"/>
                </el-form-item>
              </el-col>
              <el-col :span="8">

                <el-form-item label="备注" prop="remark">
                  <el-input v-model="form.remark"/>
                </el-form-item>
              </el-col>
<!--              <el-col :span="8">-->
<!--                <el-form-item label="绑定客户" prop="customerId">-->
<!--                  <zSelect :value.sync="form.customerId" :showNam="form.customerName" url="api/dropDown/basCustomerList" />-->
<!--                </el-form-item>-->
<!--              </el-col>-->
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="绑定多客户" >
                  <zSelect
                    ref="selectCustomer"
                    :value.sync="customerList"
                    :showName="customerListName"
                    multiple
                    url="api/dropDown/basCustomerList"
                    :params="customerParams"
                    style="width: 903px;"/>
                </el-form-item>
              </el-col>
            </el-row>

            <!--key="item.name"  disabled="level !== 1 && item.level <= level"-->
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="text" @click="crud.cancelCU">取消</el-button>
            <el-button :loading="crud.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
          </div>
        </el-dialog>
        <!--表格渲染-->
        <el-table ref="table"
                  border
                  v-loading="crud.loading"
                  :data="crud.data"
                  style="width: 100%;"
                  @selection-change="crud.selectionChangeHandler"
                  @row-dblclick="crud.toEdit($event)">
          <el-table-column :render-header="crud.renderHeader" :selectable="checkboxT" type="selection" width="60"/>
          <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('loginName')" :show-overflow-tooltip="true" label="登录名"
                           prop="loginName"/>
          <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('avatar')" :show-overflow-tooltip="true" label="头像" prop="dept"
                           width="100">
            <template slot-scope="scope">
              <el-image style="width: 60px;height: 60px;" :src="scope.row.avatar"  :preview-src-list="[scope.row.avatar]"/>
            </template>
          </el-table-column>
          <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('nickName')" :show-overflow-tooltip="true" label="昵称" prop="nickName"/>
          <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('sex')" label="性别" prop="sex">
            <template slot-scope="scope">
              <span>{{ dictName(dict.t_sys_user_sex,scope.row.sex)  }}</span>
            </template>
          </el-table-column>
          <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('phone')" :show-overflow-tooltip="true" label="电话" prop="phone"
                           width="100"/>
          <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('email')" :show-overflow-tooltip="true" label="邮箱" prop="email"
                           width="125"/>
          <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('graduateSchool')" :show-overflow-tooltip="true" label="毕业院校"
                           prop="graduateSchool"
                           width="125"/>
          <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('education')" :show-overflow-tooltip="true" label="学历"
                           prop="education"
                           width="125"/>
          <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('companyName')" :show-overflow-tooltip="true" label="公司"
                           prop="companyName"
                           width="125"/>
          <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('dept')" :show-overflow-tooltip="true" label="部门 / 岗位" prop="dept"
                           width="200">
            <template slot-scope="scope">
              <div>{{ scope.row.deptName }} / {{ scope.row.postName }}</div>
            </template>
          </el-table-column>
          <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('contactName')" :show-overflow-tooltip="true" label="紧急联系人"
                           prop="contactName"
                           width="125"/>
          <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('contactPhone')" :show-overflow-tooltip="true" label="紧急联系人电话"
                           prop="contactPhone"
                           width="125"/>
          <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('contractStartDate')" :show-overflow-tooltip="true" label="劳动合同开始日期"
                           prop="contractStartDate"
                           width="125"/>
          <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('contractEndDate')" :show-overflow-tooltip="true" label="劳动合同结束日期"
                           prop="contractEndDate"
                           width="125"/>
          <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('payPlanName')" :show-overflow-tooltip="true" label="工资方案"
                           prop="payPlanName"
                           width="125"/>
          <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('scheduleName')" :show-overflow-tooltip="true" label="班次定义"
                           prop="scheduleName"
                           width="125"></el-table-column>
          <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('status')" align="center" label="状态" prop="status">
            <template slot-scope="scope">
              <el-switch
                  v-model="scope.row.status == 1"
                  :disabled="user.id === scope.row.id"
                  active-color="#409EFF"
                  inactive-color="#F56C6C"
                  @change="changeEnabled(scope.row, scope.row.status)"
              />
            </template>
          </el-table-column>
          <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('createTime')" :show-overflow-tooltip="true" label="创建日期"
                           prop="createTime" width="140">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column
              v-permission="['admin','user:edit','user:del']"
              align="center"
              fixed="right"
              label="操作"
              width="200"
          >
            <template slot-scope="scope">
              <udOperation
                  :data="scope.row"
                  :isShow="true"
                  :disabled-dle="scope.row.id == user.id||scope.row.status ==0"
                  :permission="permission"
              />

            </template>
          </el-table-column>
        </el-table>
        <!--分页组件-->
        <pagination/>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import crudUser, { enableOrDisable,gettarget ,saveTarget} from '@/api/system/user'
import {isvalidPhone} from '@/utils/validate'
import {getDepts} from '@/api/system/dept'
import {resetPassword} from '@/api/system/user'
import { getCompany, tree, sysCompanyTree } from '@/api/system/company'
import {getAll, getLevel, sysRoleList} from '@/api/system/role'
import {getAllJob, sysPostList} from '@/api/system/job'
import CRUD, {crud, form, header, presenter} from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
// import JtgSelect from "@/components/select/jtgSelect";
import Treeselect from '@riophae/vue-treeselect'
import {mapGetters} from 'vuex'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { getToken } from "@/utils/auth";
import { getAreaTree } from '../../../api/erp/basCustomerArea'
import target from '@/components/target/index'
let userRoles = []
// crud交由presenter持有
const defaultCrud = CRUD({title: '系统用户', url: 'api/sysUser',optShow: {
    add: true,
    edit: true,
    del: true,
    download: true,
    leadingIn: true,
    enable: true,
    disable: true,
    pass: false,
    reject: false
  },
  crudMethod: {...crudUser}})
const defaultForm = {
  username: null,
  nickName: null,
  sex: '',
  email: null,
  roles: [],
  job: {id: null},
  dept: {id: null},
  phone: null,
  postId: null,
  postName: null,
  postCode: null,
  address: null,
  avatar:null,
  birthday: null,
  code: null,
  companyCode: null,
  companyId: null,
  companyName: null,
  contactName: null,
  contactPhone: null,
  contractEndDate: null,
  contractNo: null,
  contractStartDate: null,
  deptCode: null,
  deptId: null,
  deptName: null,
  education: null,
  employNature: null,
  graduateSchool: null,
  hireDate:null,
  hobbies: null,
  household: null,
  householdAddress: null,
  householdNature: null,
  idcard: null,
  leaveDate: null,
  leaveRemark: null,
  loginName: null,
  marriage: null,
  name: null,
  nation: null,
  nativePlace: null,
  otherBenefits: null,
  number: null,
  password: null,
  positiveDate: null,
  politic: null,
  realName: null,
  remark: null,
  retireDate: null,
  salaryCard: null,
  salaryStand: null,
  schemeCode: null,
  schemeId: null,
  schemeName: null,
  seq: null,
  status: null,
  shiftCode: null,
  shiftId: null,
  shiftName: null,
  subject: null,
  type: null,
  businessAttr: '',
  id: '',
  isDirectSale: 0,
  payPlanId: null,
  payPlanName: null,
  scheduleId:'',
  machineId:''
}
export default {
  name: 'sysUser',
  components: {Treeselect, crudOperation, rrOperation, udOperation, pagination,target},
  mixins: [presenter(defaultCrud), header(), form(defaultForm), crud()],
  // 数据字典
  dicts: ['t_sys_user_business_attr','t_sys_user_sex', 't_sys_politic', 't_sys_marriage'],
  data() {
    // 自定义验证
    // const validPhone = (rule, value, callback) => {
    //   if (!value) {
    //     callback(new Error('请输入电话号码'))
    //   } else if (!isvalidPhone(value)) {
    //     callback(new Error('请输入正确的11位手机号码'))
    //   } else {
    //     callback()
    //   }
    // }
    const validPhone = (rule, value, callback) => {
      if (value === '') {
        callback()
      } else if (!isvalidPhone(value)) {
        callback(new Error('请输入正确的11位手机号码'))
      } else {
        callback()
      }
    }
    const checkIdentitytionId = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("身份证号不能为空"));
      }
      if (!/(^\d{15}$)|(^\d{17}(\d|X|x)$)/.test(value)) {
        callback(new Error("你输入的身份证长度或格式错误"));
      }
      //身份证城市
      var aCity = {
        11: "北京",
        12: "天津",
        13: "河北",
        14: "山西",
        15: "内蒙古",
        21: "辽宁",
        22: "吉林",
        23: "黑龙江",
        31: "上海",
        32: "江苏",
        33: "浙江",
        34: "安徽",
        35: "福建",
        36: "江西",
        37: "山东",
        41: "河南",
        42: "湖北",
        43: "湖南",
        44: "广东",
        45: "广西",
        46: "海南",
        50: "重庆",
        51: "四川",
        52: "贵州",
        53: "云南",
        54: "西藏",
        61: "陕西",
        62: "甘肃",
        63: "青海",
        64: "宁夏",
        65: "新疆",
        71: "台湾",
        81: "香港",
        82: "澳门",
        91: "国外"
      };
      if (!aCity[parseInt(value.substr(0, 2))]) {
        callback(new Error("你的身份证地区非法"));
      }
      // 出生日期验证
      var sBirthday = (
          value.substr(6, 4) +
          "-" +
          Number(value.substr(10, 2)) +
          "-" +
          Number(value.substr(12, 2))
        ).replace(/-/g, "/"),
        d = new Date(sBirthday);
      if (
        sBirthday !=
        d.getFullYear() + "/" + (d.getMonth() + 1) + "/" + d.getDate()
      ) {
        callback(new Error("身份证上的出生日期非法"));
      }

      // 身份证号码校验
      var sum = 0,
        weights = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2],
        codes = "10X98765432";
      for (var i = 0; i < value.length - 1; i++) {
        sum += value[i] * weights[i];
      }
      var last = codes[sum % 11]; //计算出来的最后一位身份证号码
      if (value[value.length - 1] != last) {
        callback(new Error("你输入的身份证号非法"));
      }
      callback();
    };

    return {
      sections:[],
      targetlist:[],
      date:[],
      title:'',
      flag:false,
      years:[
        {value: new Date().getFullYear(),label: new Date().getFullYear()},
        {value: new Date().getFullYear()+1,label: new Date().getFullYear()+1},
      ],
      height: document.documentElement.clientHeight - 180 + 'px;',
      deptName: '', depts: [], deptDatas: [], jobs: [], level: 3, roles: [],
      companyDatas:[],
      defaultProps: {children: 'children', label: 'name'},
      areaList:[],
      permission: {
        add: ['admin', 'sysUser:add'],
        edit: ['admin', 'sysUser:edit'],
        del: ['admin', 'sysUser:del'],
        import: ['admin', 'sysUser:import'],
        export: ['admin', 'sysUser:export'],
      },
      // payPlanIds:"",
      // payPlanNames:"",
      customerList: '',
      customerListName: '',
      customerParams:{},
      headers: { Authorization: getToken() },
      businessAttr: [],
      businessAttrNum: [],
      enabledTypeOptions: [
        {key: 1, display_name: '启用'},
        {key: 0, display_name: '禁用'}
      ],
      rules: {
        loginName: [
          {required: true, message: '请输入用户名', trigger: 'blur'},
          {min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur'}
        ],
        nickName: [
          {required: true, message: '请输入用户昵称', trigger: 'blur'},
          {min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur'}
        ],
        idcard: [
          {required: true, message: '请输入身份证号', trigger:  'blur'},
          { message: '请输入正确的身份证号', trigger: 'blur',validator: checkIdentitytionId}
        ],
        nation: [
          {required: true, message: '请输入民族', trigger: 'blur'},
        ],
        politic: [
          {required: true, message: '请输入政治面貌', trigger: 'blur'},
        ],
        phone: [
          {required: true, message: '请输入电话', trigger: 'blur'},
        ],
        code: [
          {required: true, message: '请输入用户编码', trigger: 'blur'},
        ],
        email: [
          {required: true, message: '请输入邮箱地址', trigger: 'blur'},
          {type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur'}
        ],
        postId : [
          {required: true, message: '请选择岗位', trigger: 'blur'},
        ],
        roles: [
          {required: true, message: '请选择角色', trigger: 'blur'},
        ],
        // phone: [
        //   { message: '请输入正确的手机号码', trigger: 'blur',validator: validPhone}
        // ],
        deptId: [
          {required: true, trigger: 'blur', validator: this.valiDeptId}
        ],
        job: [
          {required: true, trigger: 'blur', validator: this.valiJob}
        ]
      },
      switchStatus: false,
      options: [{
        value: 1 ,
        label: '是'
      }, {
        value: 0 ,
        label: '否'
      }],
      isDirectSale: 0,
      query:{
        year:new Date().getFullYear(),
        keyword:'',

        // month:'',
        // dayTarget:'',
        // monthTarget:'',

      }
    }
  },
  computed: {
    ...mapGetters([
      'user',
      'updateAvatarApi',
      'baseApi'
    ]),
    action() {
      const baseURL =
        process.env.NODE_ENV === "production"
          ? process.env.VUE_APP_BASE_API + "/"
          : "/";
      return baseURL +"api/common/uploadImage";
    },
  },
  created() {
    this.$nextTick(() => {
      this.getDeptDatas()
      this.crud.toQuery()
      this.crud.msg.add = '新增成功，默认密码：123456'
    })
    this.getDepts()
    this.getCompanyInfo()
    this.getRoles()
    this.getRoleLevel()
    this.getJobs(null)
    getAreaTree().then(res => {
      this.areaList = res
    })
    // console.log(name)
  },
  mounted: function () {
    const that = this
    window.onresize = function temp() {
      that.height = document.documentElement.clientHeight - 180 + 'px;'
    }
  },
  watch:{
      form:{
        handler(n){
          this.switchStatus = this.form.status == 1
          // console.log('!!!!!!!!!')
          // console.log(this.form.isDirectSale)
          // if (this.form.isDirectSale === null) {
          //   this.form.isDirectSale = 0
          // }
          // this.isDirectSale = this.form.isDirectSale
        },
        deep: true
      }
  },
  methods: {
    inyear(){
        this.gettargetlist()
    },
    target(){
      if (this.crud.status.add===1){
        this.$message.error('请先确认');
      }else{
            this.title='业务员指标'
            this.flag=true
            this.gettargetlist()
      }
    },
    gettargetlist(){
      const data={
              id:this.form.id,
              year:this.query.year
            }
            gettarget(data).then(res=>{
              this.targetlist=res.data.content
              this.date=res.data
              console.log('查询指标');
            })
    },
    section(val){
      this.sections=val
    },
    save(){
      if (this.sections.length>0) {
        var data={
        targetList:this.sections,
        userId:this.form.id
      }
      }else{
        var data={
        targetList:this.targetlist,
        userId:this.form.id
      }
      }
      saveTarget(data).then(res=>{
        console.log(res,res.mag,'保存');
        this.flag=false
        this.$message({
          message: res.msg,
          type: 'success'
        })
      })
    },

    // 重置密码
    refashPass(row){
      let  ids= []
        row.map((item)=>{
        ids.push(item.id)
      })
      resetPassword({id:ids.join(',')}).then(res => {
        this.crud.notify('密码重置成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
      })
    },
    handleChange(event, item) {
      if (event) {
        this.businessAttr.push(item.value)
        this.businessAttrNum.push(item.label)
      } else {
        this.businessAttr.splice(this.businessAttr.indexOf(item.value), 1)
        this.businessAttrNum.splice(this.businessAttrNum.indexOf(item.label), 1)
      }
      this.crud.form.businessAttr = this.businessAttr.join()
    },
    changeRole(value) {
      userRoles = []
      console.log(value, 'vvvva')
      value.forEach(function (data, index) {
        const role = {id: data}
        userRoles.push(role)
      })
    },
    valiDeptId(rule, value, callback) {
      if (!this.form.deptId) {
        callback(new Error('请选择部门'))
      } else {
        callback()
      }
    },
    getNoStr(val,type,prop){
      let str = ''
      val.forEach(item=>{
        const itemNode = this.getTreeName(this[type],item)
        str = this.getNode(itemNode,str)
      })
      this.form[prop] = str
    },
    valiJob(rule, value, callback) {
      if (!this.form.postId) {
        callback(new Error('请选择岗位'))
      } else {
        callback()
      }
    },
    [CRUD.HOOK.afterAddError](crud) {
      this.afterErrorMethod(crud)
    },
    [CRUD.HOOK.afterEditError](crud) {
      this.afterErrorMethod(crud)
    },
    [CRUD.HOOK.afterToEdit](crud){
      let ids = ''
      let names = ''
      for(let i of this.form.payPlanList){
          ids += i.payPlanId+','
          names += i.payPlanName+','
      }
      if(ids){
        this.payPlanId = ids.substring(0,ids.length-1)
        this.payPlanName = names.substring(0,names.length-1)
      }else{
        this.payPlanId = ''
        this.payPlanName = ''
      }
      // this.payPlanIds = this.form.payPlanList.map(item=>item.payPlanId).join(',')
    },
    [CRUD.HOOK.beforeRefresh](crud) {
      this.crud.query = this.query
      return true
    },
    afterErrorMethod(crud) {
      // 恢复select
      const initRoles = []
      userRoles.forEach(function (role, index) {
        initRoles.push(role.id)
      })
      crud.form.roles = initRoles
    },
    deleteTag(value) {
      userRoles.forEach(function (data, index) {
        if (data.id === value) {
          userRoles.splice(index, value)
        }
      })
    },
    beforeInit() {
      this.url = 'api/users'
      return true
    },
    getTreeName(treeList,id){
      let _this=this
      for (let i = 0; i < treeList.length; i++) {
        let treeItem=treeList[i]
        if(treeItem.id===id){
          return treeItem
        }else{
          if(treeItem.children && treeItem.children.length>0){
            let res=_this.getTreeName(treeItem.children,id)
            if(res){
              return res
            }
          }
        }
      }
    },
    getNode(node,str){
      if (node.children){
        for (let i =0;i<node.children.length;i++){
          str = this.getNode(node.children[i],str)
        }
      }
      return str+=node.id+ ','
    },
    // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU](crud, form) {
      this.userid=this.form.id
      if (form.businessAttr) {
        this.form.politic = Number(form.politic)
        this.form.marriage = Number(form.marriage)
        let list = form.businessAttr.split(',')
        let info = []
        let num = []
        this.dict.t_sys_user_business_attr.map((item,i)=>{
          list.map((res,b)=>{
            if(res == item.value){
              info.push(item.label);
              num.push(item.value);
            }
          })
        })
        this.businessAttrNum=info
        this.businessAttr = num
      } else {
        this.businessAttrNum = []
        this.businessAttr = []
      }
      this.form.id = form.id
      this.customerList = form.customerList.map(item=>item.customerId).join(',')
      this.customerListName = form.customerList.map(item=>item.customerName).join(',')
      // form.status = form.status.toString()
    },
    // 打开编辑弹窗前做的操作
    [CRUD.HOOK.beforeToEdit](crud, form) {
      this.getJobs()
      userRoles = []
      const roles = []
      if(form.roles != null){
        form.roles.forEach(function (role, index) {
          roles.push(role.id)
          // 初始化编辑时候的角色
          const rol = {id: role.id}
          userRoles.push(rol)
        })
        form.roles = roles
      }
    },
    // 提交前做的操作
    [CRUD.HOOK.afterValidateCU](crud) {
      if (!crud.form.deptId) {
        this.$message({
          message: '部门不能为空',
          type: 'warning'
        })
        return false
      } else if (!crud.form.postId) {
        this.$message({
          message: '岗位不能为空',
          type: 'warning'
        })
        return false
      } else if (this.roles.length === 0) {
        this.$message({
          message: '角色不能为空',
          type: 'warning'
        })
        return false
      }

      this.form.customerList = this.customerList.split(',').map(item=>{return {customerId:item}})
      this.form.status = crud.form.status
      crud.form.roles = userRoles
      if (this.payPlanId){
        const payPlanList =this.payPlanId.toString().split(',').filter(item=>item!=='')
        this.form.payPlanList = payPlanList.map(item=>{
          return{
            payPlanId:item
          }
        })
      }
      return true
    },
    // 获取左侧部门数据
    getDeptDatas() {
      const sort = 'id,desc'
      const params = {sort: sort}
      if (this.deptName) {
        params['name'] = this.deptName
      }
      getDepts(params).then(res => {
        this.deptDatas = res
      })
    },
    // 获取弹窗内部门数据
    getDepts() {
      getDepts({status: 1,size:999}).then(res => {
        this.depts = res
      })
    },
    // 获取弹窗内公司数据
    getCompanyInfo() {
      sysCompanyTree({status: 1,size:999}).then(res => {
        this.companyDatas = res
      })
    },
    // 切换部门
    handleNodeClick(data) {
      if (data.pid === 0) {
        this.query.deptId = null
      } else {
        this.query.deptId = data.id
      }
      this.crud.toQuery()
    },
    changeEnabledPlus(val){
      this.form.status = this.form.status == 0 ?1:0
    },
    // 改变状态
    changeEnabled(data, val) {
      let info = data.status == 1?'禁用':'启用'
      this.$confirm('此操作将 "' + info + '" ' + data.nickName + ', 是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let infoS = {
          ids:[data.id],
          type: data.status == 1?'DISABLE': 'ENABLE'
        }
        crudUser.enableOrDisable(infoS).then(res => {
          this.crud.notify(info + '成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
          this.crud.toQuery()
        }).catch(() => {
          // data.status = !data.status
        })
      }).catch(() => {
        // data.status = !data.status
      })
    },
    // 获取弹窗内角色数据
    getRoles()
    {
      sysRoleList({size:999}).then(res => {
        this.roles = res.content
      }).catch(() => {
      })
    },
    // 获取弹窗内岗位数据
    getJobs(id) {
      sysPostList(id).then(res => {
        this.jobs = res.content
      }).catch(() => {
      })
    },
    // 点击部门搜索对应的岗位
    selectFun(node, instanceId) {
      this.getJobs(node.id)
      this.form.job.id = null
    },
    // 获取权限级别
    getRoleLevel() {
      getLevel({size:999}).then(res => {
        this.level = res.level
      }).catch(() => {
      })
    },
    upStatus(s){
      this.form.status = s?1:0
    },
    checkboxT(row, rowIndex) {
      return row.id !== this.user.id && !row.enabled
    },
    normalizer(node) {
      //去掉children=[]的children属性
      if (node.children == null || node.children.length == 0) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      }
    },
    handleAvatarSuccess(res, file) {
      this.form.avatar = file.response.data.path;
      // this.form.avatar = URL.createObjectURL(file.raw);
    },
    handleError(err, file, fileList) {
      this.crud.notify(
        " -_- !~~ 服务器开小差了，稍后重试",
        CRUD.NOTIFICATION_TYPE.WARNING
      );
    },
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2;

      const isJPG = file.type === 'image/jpeg' ||
        file.type === 'image/png' ||
        file.type === 'image/gif' ||
        file.type === 'image/jpg'
      // const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG、JPEG、PNG、GIF 格式!')
        return false
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    }
  }
}
</script>

<style scoped>
.line-tips{
  margin: 20px 0;
  font-size: 16px;
  font-weight: 600;
  color: #000000;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}
.avatar {
  width: 100px;
  height: 100px;
  border: 1px solid #ddd;
  display: block;
}
</style>
